package com.advertisementsystem.adservice.controller;

import com.advertisementsystem.adservice.entity.Ad;
import com.advertisementsystem.adservice.entity.AdCategory;
import com.advertisementsystem.adservice.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/ads")
public class AdController {

    @Autowired
    private AdService adService;

    @GetMapping
    public List<Ad> findAll() {
        return adService.findAll();
    }

    @GetMapping("/{id}")
    public Ad findById(@PathVariable Integer id) {
        return adService.findById(id);
    }

    @PostMapping
    public String save(@RequestBody Ad ad) {
        int result = adService.save(ad);
        return result > 0 ? "success" : "error";
    }

    @PutMapping("/{id}")
    public String update(@PathVariable Integer id, @RequestBody Ad ad) {
        ad.setId(id);
        int result = adService.save(ad);
        return result > 0 ? "success" : "error";
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id) {
        int result = adService.delete(id);
        return result > 0 ? "success" : "error";
    }

    @GetMapping("/categories")
    public List<AdCategory> findAllCategories() {
        return adService.findAllCategories();
    }

    @GetMapping("/categories/{id}")
    public AdCategory findCategoryById(@PathVariable Integer id) {
        return adService.findCategoryById(id);
    }

    @PostMapping("/categories")
    public String saveCategory(@RequestBody AdCategory category) {
        int result = adService.saveCategory(category);
        return result > 0 ? "success" : "error";
    }

    @PutMapping("/categories/{id}")
    public String updateCategory(@PathVariable Integer id, @RequestBody AdCategory category) {
        category.setId(id);
        int result = adService.updateCategory(category);
        return result > 0 ? "success" : "error";
    }

    @DeleteMapping("/categories/{id}")
    public String deleteCategory(@PathVariable Integer id) {
        int result = adService.deleteCategory(id);
        return result > 0 ? "success" : "error";
    }

    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String imagePath = adService.uploadImage(file);
            return imagePath;
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }
}